﻿using Entity.ProjectEnt;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using NPOIDemo;
using ZFine.Application;
using ZFine.Application.Project;
using ZFine.Application.SystemSecurity;
using ZFine.Code;
using ZFine.Domain.Entity;
using ZFine.Web;

namespace Logiv.WEB.Areas.Project.Controllers
{
    public class CarriageBoxController : BaseController
    {
        private CarriageBoxApp serverApp = new CarriageBoxApp();
        private CustomerAndThingsNameApp CTApp = new CustomerAndThingsNameApp();
        private CarriageApp carriageApp = new CarriageApp();
        private GudaoCarApp gudaoCarApp = new GudaoCarApp();


        public override ActionResult Index()
        {
            ViewData["boxTypx"] = CTApp.GetList(f => f.Type == 2 && f.State == true);
            return View();
        }

        public ActionResult AddBoxToCar(string keyVaules)
        {
            Pagination pagination2 = new Pagination();
            pagination2.sord = "F_CreatorTime desc";
            pagination2.sidx = "F_CreatorTime";
            pagination2.page = 1;
            pagination2.rows = 1000000000;
            GudaoCarEntity GudaoCarEntity = gudaoCarApp.GetForm(keyVaules);
            List<CarriageBoxEntity> carriageBoxes;
            if (GudaoCarEntity != null && GudaoCarEntity.BelongCarriage != null && !string.IsNullOrEmpty(GudaoCarEntity.BelongCarriage.CarriageID))
            {
                carriageBoxes = serverApp.GetListByCarriageChangeCarCode(GudaoCarEntity.BelongCarriage.CarriageID, pagination2);
                ViewBag.carriageBoxs = carriageBoxes.ToJson();
                ViewBag.carriageID = GudaoCarEntity.BelongCarriage.CarriageID;
            }
            List<CarriageBoxEntity> EmptyCarriageBoxList = serverApp.GetEmptyCarBoxList(pagination2);
            ViewBag.emptyCarriageBoxList = EmptyCarriageBoxList.ToJson();
            return View();
        }


        public override ActionResult Form()
        {
            var keyValue = Request.QueryString["keyValue"];
            ViewData["objs"] = serverApp.GetForm(keyValue);
            ViewData["ThingsName"] = CTApp.GetList(f => f.Type == 0 && f.State == true);
            ViewData["boxTypx"] = CTApp.GetList(f => f.Type == 2 && f.State == true);
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, string keyword, string StartTime, string EndTime,string Daozhan,string Zhuangche,string Xiangzhu)
        {
            try
            {
                var data = new
                {
                    rows = serverApp.GetList(pagination, keyword, StartTime, EndTime, Daozhan,Zhuangche,Xiangzhu),
                    total = pagination.total,
                    page = pagination.page,
                    records = pagination.records
                };
                return Content(data.ToJson());

            }
            catch (Exception ex)
            {
                return null;
            }
        }
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = serverApp.GetForm(keyValue);
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValue)
        {
            int result = serverApp.DeleteForm(keyValue);
            if (result == -1)
            {
                return Warn("请选择要删除的项");
            }
            else if (result == -2)
            {
                return Warn("没有权限对此进行删除");
            }
            return Success("删除成功。");
        }
        /// <summary>
        /// 删除箱号和车的绑定关系
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult RemoveBindInfo(string keyValue)
        {
            var thisModifEntity = serverApp.GetForm(keyValue);
            if (thisModifEntity != null)
            {
                if (thisModifEntity.ChangeBelongCarriageId == null && thisModifEntity.ChangeBelongTime == null)
                {
                    return Error("此箱号未绑定车，无需解除绑定");
                }
                serverApp.DeleteForm(thisModifEntity.F_Id);
                var newThisEntity = ZFine.Code.Json.ToObject<CarriageBoxEntity>(thisModifEntity.ToJson());
                newThisEntity.ChangeBelongCarriageId = null;
                newThisEntity.ChangeBelongTime = null;
                newThisEntity.LeaveTime = null;
                serverApp.SubmitForm(newThisEntity, "");

                #region 日志记录
                LogEntity logEntity = new LogEntity();
                var LoginInfo = OperatorProvider.Provider.GetCurrent();
                logEntity.F_ModuleName = "箱号绑定解除";
                logEntity.F_Type = DbLogType.Update.ToString();
                if (LoginInfo != null)
                {
                    logEntity.F_Account = LoginInfo.UserId;
                    logEntity.F_NickName = LoginInfo.UserName;
                }
                logEntity.F_Description = thisModifEntity.ToJson() + " - " + newThisEntity.ToJson();
                new LogApp().WriteDbLog(logEntity);
                #endregion
            }
            else
            {
                return Error("修改对象不存在，");
            }
            return Success("消除绑定成功");
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateInput(false)]
        public ActionResult SubmitForm(CarriageBoxEntity NewsEntity, string keyValue)
        {
            int result = serverApp.SubmitForm(NewsEntity, keyValue);
            if (result == -1)
            {
                return Error("找不到对象");
            }
            else
            {
                return Success("操作成功。");
            }
        }

        public JsonResult AddChangeBelongCarriageBoxList(List<object> thispar)
        {
            string msg = string.Empty;
            int code = 0;
            string data = Request["jsonData"];
            if (!string.IsNullOrEmpty(data))
            {

                List<CarriageBoxEntity> objlist = ZFine.Code.Json.ToList<CarriageBoxEntity>(data);
                List<CarriageBoxEntity> insertObjList = new List<CarriageBoxEntity>();
                CarriageEntity carriageEntity;
                if (objlist != null && objlist.Count > 0)
                {
                    carriageEntity = carriageApp.GetFormByCarCodeId(objlist[0].ChangeBelongCarriageId);
                    for (int i = 0; i < objlist.Count; i++)
                    {
                        var tempCarriageBox = serverApp.GetEntityByCarriageBoxId(objlist[i].CarriageBoxID);
                        if (tempCarriageBox != null)
                        {
                            tempCarriageBox.ChangeBelongCarriageId = objlist[i].ChangeBelongCarriageId;
                            tempCarriageBox.ChangeBelongTime = DateTime.Now;
                            tempCarriageBox.ChangeWeight =
                                carriageEntity == null ? "" : carriageEntity.Weight.ToString();
                            tempCarriageBox.Modify(tempCarriageBox.F_Id);
                            insertObjList.Add(tempCarriageBox);
                        }
                    }
                    code = serverApp.SubmitSaveList(insertObjList);
                    msg = " 箱号绑定成功";
                }
                else
                {
                    code = -1;
                    msg = "传入数据为空";
                }
            }
            else
            {
                code = -1;
                msg = "传入数据为空";
            }
            return Json(new { msg = msg, code = code }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult GetGridExportExcell(string keyword, string StartTime, string EndTime, string Daozhan, string Zhuangche, string Xiangzhu)
        {

            Pagination pagination2 = new Pagination();
            pagination2.sord = "F_CreatorTime desc";
            pagination2.sidx = "F_CreatorTime";
            pagination2.page = 1;
            pagination2.rows = 1000000000;
            try
            {
                List<CarriageBoxEntity> carriageBoxList = serverApp.GetExportList(pagination2, keyword, StartTime, EndTime, Daozhan, Zhuangche,Xiangzhu);
                List<CarriageBoxEntity> carriageBoxEmptyBoxList = (from carBox in carriageBoxList where carBox.Remark == "坏" select carBox).OrderByDescending(f => f.LeaveTime).ToList();//坏箱
                List<CarriageBoxEntity> carriageBoxHaveWeightBoxList = (from carBox in carriageBoxList where carBox.ChangeWeight != null && carBox.Remark != "坏" select carBox).OrderByDescending(f => f.LeaveTime).ToList();//重箱
                List<CarriageBoxEntity> carriageBoxNotWeightBoxList = (from carBox in carriageBoxList where carBox.ChangeWeight == null && carBox.Remark != "坏" select carBox).OrderByDescending(f => f.LeaveTime).ToList();//空箱

                ExcelBuilder excel = new ExcelBuilder();
                Dictionary<string, List<CarriageBoxEntity>> insertDictionary =
                    new Dictionary<string, List<CarriageBoxEntity>>();
                insertDictionary.Add("坏箱", carriageBoxEmptyBoxList);
                insertDictionary.Add("重箱", carriageBoxHaveWeightBoxList);
                insertDictionary.Add("空箱", carriageBoxNotWeightBoxList);
                var boxType = CTApp.GetList(f => f.Type == 2 && f.State == true);
                HSSFWorkbook wk= excel.ReadExcel(insertDictionary, boxType);

                string fileName = "集装箱交接箱流表" + DateTime.Now + ".xls";
                MemoryStream ms = new MemoryStream();
                wk.Write(ms);
                ms.Flush();
                //ms.Position = 0;
                RenderToBrowser(ms, fileName);
                
            }
            catch (Exception ex)
            {

                return null;
            }
            return null;
        }

     


        static void RenderToBrowser(MemoryStream ms, string fileName)
        {
            byte[] bt = ms.ToArray();
            System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            //解决浏览器中文编码问题
            if (System.Web.HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
            {
                fileName = System.Web.HttpUtility.UrlPathEncode(fileName);
            }
            if (System.Web.HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
            {
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            }
            else
            {
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            }
            int lengtn = bt.Length;
            System.Web.HttpContext.Current.Response.BinaryWrite(bt);
            System.Web.HttpContext.Current.Response.Flush();
            System.Web.HttpContext.Current.Response.End();

        }
        //private ICellStyle SetStyle(ref HSSFWorkbook workbook) {
        //    ICellStyle style = workbook.CreateCellStyle();
        //    style.Alignment = HorizontalAlignment.Center;//设置单元格的样式：水平对齐居中
        //    style.VerticalAlignment = VerticalAlignment.Center;//设置单元格样式：垂直对齐居中
        //    IFont font = workbook.CreateFont();//新建一个字体样式对象
        //    font.Boldweight = short.MaxValue;
        //    style.SetFont(font);
        //    return style;
        //}
    }
    }